<?php

namespace app\admin\controller\user;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,account,nickname';
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->admin = new \app\admin\model\Admin;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $auth_group_access = \think\Db::name('auth_group_access')->where('uid', $this->auth->id)->find();
            if (empty($auth_group_access)) {
                $merchant = [];
            } elseif ($auth_group_access['group_id'] == 2) {
                $merchant = ['merchant_id' => $this->auth->id];
            } else {
                $merchant = [];
            }
            $list = $this->model
                ->with(['group', 'merchant', 'lvl'])
                ->where($where)
                ->where($merchant)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                if ($v['group_id'] == 1) {
                    $v->merchant['username'] = empty($v->merchant->id) ? '平台会员' : $v->merchant->username;
                } else {
                    $v->merchant['username'] = '平台客服';
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取员工列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @throws \think\exception\DbException
     * @author yuncran@126.com
     */
    public function merchant()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $authGroupList = AuthGroupAccess::where('group_id', 2)->column('uid');
            $pageNumber = $this->request->request('pageNumber');
            $username = $this->request->request('searchValue');
            $number = empty($pageNumber) || $pageNumber == 1 ? 0 : $pageNumber;
            $pageSize = 10;
            $list = $this->admin
                ->where('id', 'in', $authGroupList)
                ->where(function ($query) use ($username) {
                    if (!empty($username)) {
                        $query->where('id', $username);
                    }
                })
                ->field(['password', 'salt', 'token'], true)
                ->order('id', 'desc')
                ->limit($number, $pageSize)
                ->select();
            $total = $this->admin->where('id', 'in', $authGroupList)->count();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), ['class' => 'form-control selectpicker']));
            $statusList = ['normal' => __('正常'), 'hidden' => __('禁闭')];
            $this->assign("statusList", $statusList);
            $gender = ['0' => __('女'), '1' => __('男'), '3' => __('客服身份')];
            $this->assign("typeList", $this->model->getTypeList());
            $this->assign("gender", $gender);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $res = $this->model->whereOr('nickname', $params['nickname'])->whereOr('email', $params['email'])->whereOr('account', $params['account'])->find();
            if ($res) {
                $this->error(__('您输入的昵称重复了'));
            }
            $salt = \fast\Random::alnum();
            $params['password'] = \app\common\library\Auth::instance()->getEncryptPassword($params['password'], $salt);
            $params['salt'] = $salt;
            $result = $this->model->allowField(true)->save($params);
            Db::name('user_census_count')->insert([
                'user_id' => $this->model->getLastInsID(),
                'create_time' => time(),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $this->view->assign("typeList", $this->model->getTypeList());

        $authGroupList = AuthGroupAccess::where('group_id', 2)->column('uid');
        $list = $this->admin
            ->where('id', 'in', $authGroupList)
            ->field(['password', 'salt', 'token'], true)
            ->order('id', 'desc')
            ->select();
        $new_array = [];
        $unshift = ['id' => 0, 'username' => '平台会员'];
        foreach ($list as $key => $value) {
            $new_array[$key] = $value;
        }
        array_unshift($new_array, $unshift);
        $this->view->assign("merchantList", $new_array);
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    public function recommend()
    {
        $ids = $this->request->post('ids');
        $row = $this->model->get($ids);
        $result = $row->save([
            'is_recommend' => $row->is_recommend == 0 ? 1 : 0,
            'updatetime' => time()
        ]);
        $this->success();
    }

    /**
     * 会员相册
     * @param $ids
     * @return \think\response\Redirect
     * @author yuncran@126.com
     */
    public function getUserPhoto($ids = null)
    {
        $url = url('image/UserImage/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }


    /**
     * 会员动态
     * @return void
     * @author yuncran@126.com
     */
    public function getTrends($ids = null)
    {
        $url = url('trends/Trends/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    /**
     * 会员黑名单
     * @param $ids
     * @return \think\response\Redirect
     * @author yuncran@126.com
     */
    public function getBlackList($ids = null)
    {
        $url = url('blacklist/UserBlacklist/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    /**
     * 会员充值记录
     * @param $ids
     * @return \think\response\Redirect
     * @author yuncran@126.com
     */
    public function getRechargeLog($ids = null)
    {
        $url = url('recharge/Recharge/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    public function getGiftLog($ids = null)
    {
        $url = url('gift/BuyGiftLog/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    /**
     * 会员点赞会员
     * @param $ids
     * @return \think\response\Redirect
     * @author yuncran@126.com
     */
    public function getGive($ids = null)
    {
        $url = url('give/UserGive/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    /**
     * 关注会员
     * @param $ids
     * @return \think\response\Redirect
     * @author yuncran@126.com
     */
    public function getUserFollow($ids = null)
    {
        $url = url('give/UserGive/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

    public function getUserLog($ids = null)
    {
        $url = url('user/userMoneyLog/index?' . 'user_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }


    public function friend($ids = null)
    {
        $url = url('friend/Friend/index?' . 'use_id=' . $ids);
        // 重定向用户
        return redirect($url);
    }

}
